$(function() {
    var bdbDomainTpl = {
        /* 初始数据 */
        defData: {
            pageSize: 20 // 每页分页数量.
        },

        /* 页面状态 */
        pageState: {
            search: '', // 搜索框值.
            page: 1, // 分页值.
            noData: 'def' // search: 没有匹配的结果; def: 暂无记录.
        },
        resetPageState: function() {
            this.pageState = {
                search: '', // 搜索框值.
                page: 1, // 分页值.
                noData: 'def' // search: 没有匹配的结果; def: 暂无记录.
            };

            this.list();
        },

        /* 添加 */
        addEvent: function() {
            var _this = this,
                formVerify;

            // 表单验证.
            formVerify = $('#bdb-domain-tpl-add-form').validate({
                // onkeyup: false,
                errorElement: "div",
                errorPlacement: function (error, element) {
                    error.addClass("help-block");
                    if (element.prop("type") === "checkbox" || element.prop("type") === "radio") {
                        error.appendTo(element.parents(".bdb-vc"));
                    } else {
                        error.insertAfter(element);
                    }
                },
                submitHandler: function(form, e) {
                    e.preventDefault();
                    _this.addSave(form);
                }
            });

            // .
            _this.addVerifyFocusout();
            _this.recordTypeChange();

            // 点击添加响应事件.
            $('#bdb-domain-tpl-add').off('click').on('click', function(){
                _this.addDefDataProc(formVerify);
            });
        },
        addDefDataProcTpl: function(data) {
            var tpl = '',
                k = 0,
                redStat = '',
                firstRecord = '';

            $.each(data.lineList, function(i, n) {
                if (k == 0) {
                    redStat = '<span class="bdb-f-c-ff3900">*</span>';
                    firstRecord = 'id="record[0][master]" data-rule-required="true" data-msg-required="请输入ip" \
                                     data-rule-srcTplMasterProc="true" data-msg-srcTplMasterProc="ip格式错误" \
                                     placeholder="' + bdbMain.attr.placeholder.ip + '"';
                }

                tpl += '<div class="form-group bdb-tpl-add-row">\
                            <div class="bdb-l-h-32 bdb-col-1">' + redStat + n + '</div>\
                            <div class="bdb-col-2 bdb-form-select-wrapper bdb-p-r">\
                                <div class="top-arrow"></div>\
                                    <select class="bdb-form-select js-bdb-srcTplType" name="record[' + i +'][type]">\
                                        <option value="A">A</option>\
                                        <option value="CNAME">CNAME</option>\
                                    </select>\
                                <div class="bottom-arrow"></div>\
                            </div>\
                            <div class="bdb-col-3">\
                                <input type="text" class="bdb-form-control js-bdb-srcTplMaster" name="record[' + i +'][master]" autocomplete="off" ' + firstRecord + '>\
                            </div>\
                            <div class="bdb-col-4">\
                                <input type="text" class="bdb-form-control js-bdb-srcTplSlave" name="record[' + i + '][bak]" autocomplete="off">\
                            </div>\
                       </div>';

                if (k == 0) {
                    redStat = '';
                    firstRecord = '';
                    ++k;
                }
            });

            return tpl;
        },
        addVerifyFocusout: function() {
            $('#bdb-domain-tpl-add-form #bdb-tpl-add-list').off('focusout').on('focusout', 'input', function() {
                var msgEle = $(this).parents(".form-group"),
                    _this = $(this);

                if (msgEle.find(".js-bdb-srcTplType").val() == 'A') {
                    if (_this.val() != '') {
                        if (_this.attr("name").indexOf('master') > -1) {
                            _this.rules("add", {
                                required: true,
                                srcTplMasterProc: true,
                                messages: {
                                    required: '请输入ip',
                                    srcTplMasterProc: "ip格式错误"
                                }
                            });
                        } else {
                            _this.rules("add", {
                                required: true,
                                srcTplSlaveProc: true,
                                srcTplMSCompareProc: true,
                                srcTplMRequiredProc: true,
                                messages: {
                                    required: '请输入ip',
                                    srcTplSlaveProc: "ip格式错误",
                                    srcTplMSCompareProc: "主、备ip不能相同",
                                    srcTplMRequiredProc: "主ip为必填项"
                                }
                            });
                        }
                    } else {
                        _this.rules("remove");
                    }
                } else {
                    if (_this.val() != '') {
                        _this.rules("add", {
                            required: true,
                            srcTplMasterProc: true,
                            messages: {
                                required: '请输入CNAME',
                                srcTplMasterProc: "请输入正确的CNAME"
                            }
                        });
                    } else {
                        _this.rules("remove");
                    }
                }
            });
        },
        recordTypeChange: function() {
            $('#bdb-domain-tpl-add-form #bdb-tpl-add-list').off('change').on('change', '.js-bdb-srcTplType', function() {
                var _this = $(this),
                    msgEle = _this.parents('.bdb-tpl-add-row'),
                    master = msgEle.find('.js-bdb-srcTplMaster'),
                    slave = msgEle.find('.js-bdb-srcTplSlave');

                if (_this.val() == 'A') {
                    master.val('');
                    master.rules('remove');

                    if (master.attr('id') == 'record[0][master]') {
                        master.attr({'placeholder': bdbMain.attr.placeholder.ip});
                        master.rules('add', {
                            required: true,
                            srcTplMasterProc: true,
                            messages: {
                                required: '请输入ip',
                                srcTplMasterProc: 'ip格式错误'
                            }
                        });
                    }

                    slave.val('');
                    slave.rules('remove');

                    slave.show();
                    master.siblings().remove();
                } else {
                    master.val('');
                    master.rules('remove');

                    if (master.attr('id') == 'record[0][master]') {
                        master.attr({'placeholder': ''});
                        master.rules('add', {
                            required: true,
                            srcTplMasterProc: true,
                            messages: {
                                required: '请输入CNAME',
                                srcTplMasterProc: '请输入正确的CNAME'
                            }
                        });
                    }

                    slave.val('');
                    slave.rules('remove');

                    slave.hide();
                    master.siblings().remove();
                    slave.siblings().remove();
                }

                msgEle.find('.has-error').removeClass('has-error');
            });
        },
        addDefDataProc: function(formVerify) {
            var _this = this;
            bdbMain.mLRManag({mask: true, loading: true});
            $.post('/CustomerDomainTemplate/domainTemplateInit', function(response) {
                if (response.code == 0) {
                    var listHtml = _this.addDefDataProcTpl(response.data);
                    $("#bdb-domain-tpl-add-dialog #bdb-tpl-add-list").html(listHtml);
                    bdbMain.mLSleep({loading: false}, function() {
                        $('#bdb-domain-tpl-add-form').find('.js-bdb-srcTplMaster, .js-bdb-srcTplSlave').blur();

                        $(".bdbBlankEle").bdbDialog({
                            ele: '#bdb-domain-tpl-add-dialog',
                            formObj: formVerify,
                            form: $('#bdb-domain-tpl-add-form'),
                            reset: true
                        });
                    });
                } else {
                    bdbMain.mLSleep({mask: false, loading: false, alert: {type: 2, msg: response.msg}});
                }
            }, 'json');
        },
        addSave: function(form) {
            var _this = this,
                form = $(form);

            // 请求已发出.
            if (!bdbMain.ajaxInfo.state) {
                bdbMain.mLRManag({alert: {type: 2, msg: bdbMain.ajaxInfo.text}});
                return ;
            }

            // 发送请求.
            bdbMain.ajaxInfo.state = 0; // 加锁.
            bdbMain.mLRManag({mask: true, maskUp: 101, loading: true});
            $.post('/CustomerDomainTemplate/addDomainTemplate', form.serialize(), function(response) {
                if (response.code == 0) {
                    $(".js-bdb-dialog-cancel").click();
                    bdbMain.mLRManag({maskDown: 99, loading: false, alert: {type: 1, msg: '添加成功.'}});
                    bdbMain.mLSleep({}, function() {
                        _this.resetPageState();
                    });
                } else {
                    bdbMain.mLSleep({maskDown: 99, loading: false, alert: {type: 2, msg: response.msg}});
                }

                bdbMain.ajaxInfo.state = 1; // 释放锁.
            });
        },

        /* 搜索 */
        searchEvent: function() {
            var _this = this,
                searchInputEle = $('.bdb-search-input');

            searchInputEle.off('focusin').on('focusin', '.search-text', function(e) {
                var _cThis = $(this),
                    _btnEle = $(this).parent().find('span');

                if (!_btnEle.hasClass('search-clear')) {
                    _cThis.animate({width: '240px'}, 500);
                    _btnEle.animate({left: '240px'}, 500, function() {
                        _btnEle.removeClass('search-gray').addClass('search-blue');
                    });
                }
            });

            searchInputEle.off('click').on('click', 'span', function(e) {
                var left = parseInt($(this).css('left'));
                if ($(this).hasClass('search-blue') && left > 0) {
                    _this.pageState.search = searchInputEle.find('.search-text').val();
                    _this.pageState.noData = 'search';
                    $(this).removeClass('search-blue').addClass('search-clear');
                    _this.list();
                } else if (left > 0) {
                    _this.pageState.search = '';
                    _this.pageState.noData = 'def';
                    searchInputEle.find('.search-text').val('');
                    $(this).removeClass('search-clear').addClass('search-blue');
                    _this.list();
                }
            });
        },
        searchProc: function() {
        
        },

        /* 列表 */
        listEvent: function() {
            var _this = this;

            $('.bdb-list').off('click.listEvent').on('click.listEvent', function(e) {
                var ele = $(e.target),
                    id = ele.parents('.bdb-list-row').attr('data-id');

                if (ele.hasClass('js-bdb-domain-tpl-del')) { // 删除.
                    _this.listDel(id);
                }
            });
        },
        listDel: function(id) {
            var _this = this;

            bdbMain.confirm({
                textInfo: {
                    content: '确定要删除源站模版？',
                    btn: {}
                },
                // note: true,
                params: {
                    url: '/CustomerDomainTemplate/deleteDomainTemplate',
                    data: {
                        id: id
                    }
                },
                callback: function(ele, params) {
                    _this.listDelCallbackProc(ele, params);
                }
            });
        },
        listDelCallbackProc: function(ele, params) {
            var _this = this;
            ele.hide();

            // 请求已发出.
            if (!bdbMain.ajaxInfo.state) {
                bdbMain.mLRManag({alert: {type: 2, msg: bdbMain.ajaxInfo.text}});
                return ;
            }

            // 发送请求.
            bdbMain.ajaxInfo.state = 0; // 加锁.
            bdbMain.mLRManag({mask: true, loading: true});
            $.post(params.url, {
                templateId: params.data.id
            }, function(response) {
                if (response.code == 0) {
                    bdbMain.mLRManag({mask: false, loading: false, alert:{type: 1, msg: '删除成功'}});
                    bdbMain.mLSleep({}, function() {
                        _this.list({page: _this.pageState.page});
                    });
                } else {
                    bdbMain.mLSleep({mask: false, loading: false, alert:{type: 2, msg: response.msg}});
                }

                bdbMain.ajaxInfo.state = 1; // 释放锁.
            });
        },
        listProc: function(data) {
            var tpl = '';
            $.each(data.templateList, function(i, n) {
                tpl += '<div class="bdb-list-row" data-id="' + n.template_id + '">\
                            <div class="bdb-mx-w-col1 bdb-ellipsis">' + n.template_name + '</div>\
                            <div class="bdb-mx-w-col2">' + n.create_time + '</div>\
                            <div class="bdb-mx-w-col3">\
                                <div class="bdb-option-btn bdb-p-r bdb-mgn-t-10">\
                                    <a href="/CustomerDomainTemplate/setDomainTemplate/' + n.template_id + '">设置</a>\
                                    <div class="v-line-ffa007"></div>\
                                    <a class="bdb-f-c-c8baac bdb-mgn-l--1 js-bdb-domain-tpl-del" href="javascript:void(0);">删除</a>\
                                </div>\
                            </div>\
                        </div>';
            });

            return tpl;
        },
        list: function(obj) {
            var _this = this,
                obj = obj || {page: 1};

            _this.pageState.page = obj.page;
            bdbMain.mLRManag({mask: true, loading: true});

            // 获取列表.
            $.post('/CustomerDomainTemplate/domainTemplateList', {
                pageSize: _this.defData.pageSize,
                pageNumber: _this.pageState.page,
                templateName: _this.pageState.search
            }, function(response) {
                var totalRowCnt = 0,
                    listHtml = '';

                if (response.code == 0) {
                    totalRowCnt = parseInt(response.data.totalCount) > 0 ? parseInt(response.data.totalCount) : 0;
                    listHtml = _this.listProc(response.data);
                    _this.listNull(totalRowCnt);
                    $('.bdb-list').html(listHtml);
                    bdbMain.mLSleep({mask: false, loading: false});

                    // 分页插件.
                    $("#js-bdb-creatPage").bdbPagination({
                        totalRowCnt: totalRowCnt,
                        currentPage: _this.pageState.page,
                        pageSize: _this.defData.pageSize
                    });
                    $('.bdb-record-cnt').html(bdbMain.pageInfo.recordCnt.replace('{cnt}', totalRowCnt));
                } else {
                    bdbMain.mLSleep({mask: false, loading: false, alert: {type: 2, msg: response.msg}});
                }
            });
        },
        listNull: function(totalRowCnt) {
            var noResult = $('.bdb-no-result'),
                noSearchRecord = $('.bdb-no-search-record');

            if (totalRowCnt <= 0) {
                if (this.pageState.noData == 'search') { // 查询.
                    noResult.hide();
                    noSearchRecord.show();
                } else { // 暂无记录.
                    noResult.show();
                    noSearchRecord.hide();
                }
            } else {
                noResult.hide();
                noSearchRecord.hide();
            }
        },

        /* 分页 */
        pageEvent: function() {
            var　_this = this;

            /* 页码事件 */
            $('.bdb-creatPage').off('click').on('click', '.bdb-pagination', function(e) {
                e.preventDefault();
                var ele = $(e.target),
                    page = parseInt(ele.text());

                if (!isNaN(page)) {
                    _this.list({page: page});
                } 
            }); 
        },

	  	/* 屏幕高度适应 */
	  	contentSizeResize: function () {
			$(window).resize(function() {
			  	$('.bdb-list').bdbScreenH(1);
			});
		},

        /* 初始化 */
        init: function() {
            var _this = this;

            _this.addEvent();
            _this.list();
            _this.listEvent();
            _this.pageEvent();
            _this.searchEvent();
			_this.contentSizeResize(); // 内容区域屏幕适应.

            $('.bdb-list').bdbScreenH(1); // 右侧列表区域自适应.
        }
    };

    bdbDomainTpl.init();
});
